#include "highgui.h"
#include "cv.h"
#include <stdio.h>

#define ARG1 50
#define ARG2 0 //filt

int mark[2000];
int main(int argc,char** argv){

	IplImage *in=cvLoadImage(argv[1],0),*out;
	int x,y,i,
	    wanted=0,wanted_end=in->height;
	int mode=1;

	for(y=0;y<in->height;y++){
		unsigned char *ptr=(unsigned char *)(
				in->imageData+y*in->widthStep);
		//find start
		int startornot=1;
		if(mode==1){
			int index_mark=0;
			int is_the_one_ornot=1;
			memset(mark,0,sizeof(mark));
			for(x=0;x<in->width;x++){
				//if is start and the pixel is black
				if(startornot && ptr[x] <= 128){
					printf("y=%d,x=%d is black and is the start point\n",y,x);
					//printf("%d",ptr[x]);
					startornot=0;
					mark[index_mark++]=x;
				}
				//if white
				if(ptr[x] > 128)	startornot=1;
				else	startornot=0;
			}
			printf("y=%d\n",y);
			for(i=0;i<index_mark;i++)
				printf("%d ",mark[i]);
			printf("\n");
			//check to see is "the one" or not
			//0 to 7
			//use 1 to 6
			if(index_mark<7)	continue;
			if(mark[2]>in->width/2)	continue;
			if(mark[5]<in->width/2)	continue;
			int delta=mark[2]-mark[1];
			for(i=1;i<=5;i++){
				if(delta-(mark[i+1]-mark[i])>=ARG1
				&& delta-(mark[i+1]-mark[i])<=(-1)*ARG1)
					is_the_one_ornot=0;
				delta=mark[i+1]-mark[i];
			}
			if(is_the_one_ornot){
				wanted=y;
				printf("%d is the wanted line\n",y);
				mode=2;
				continue;
			}
		}
		else if(mode==2){
			//find end
			int dot_count=0;
			for(x=0;x<in->width;x++)
				if(ptr[x] < 128)
					dot_count++;
			if(dot_count<=ARG2){
				wanted_end=y;
				printf("%d is the wanted end line\n",y);
				break;
			}
		}
	}
	printf("wanted=%d\twanted_end=%d\n",wanted,wanted_end);
	cvSetImageROI(in,cvRect(0,wanted,in->width,wanted_end-wanted));
	out=cvCreateImage(cvSize(in->width,wanted_end-wanted),in->depth,in->nChannels);
	cvCopy(in,out,0);
	cvSaveImage("area_first_out.jpg",out,0);
	cvReleaseImage(&out);
	return 0;
}
